package com.dlc.shop.distribution.common.listener;

import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.dlc.shop.bean.enums.ProdStatusEnums;
import com.dlc.shop.bean.event.ProdChangeEvent;
import com.dlc.shop.bean.event.ProdChangeStatusEvent;
import com.dlc.shop.bean.model.Product;
import com.dlc.shop.bean.order.GeneralActivitiesOrder;
import com.dlc.shop.bean.vo.DistributionConfigVO;
import com.dlc.shop.common.config.Constant;
import com.dlc.shop.common.util.Json;
import com.dlc.shop.distribution.common.constants.AutoCheckEnum;
import com.dlc.shop.distribution.common.constants.DistributionProdStateEnum;
import com.dlc.shop.distribution.common.model.DistributionProd;
import com.dlc.shop.distribution.common.service.DistributionProdService;
import com.dlc.shop.service.SysConfigService;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.event.EventListener;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.util.List;
import java.util.Objects;

/**
 * @author yami
 */
@Slf4j
@Component("distributionProdChangeListener")
@AllArgsConstructor
public class ProdChangeListener {

    private final SysConfigService sysConfigService;
    private final DistributionProdService distributionProdService;


    @EventListener(ProdChangeEvent.class)
    public void prodChangeEvent(ProdChangeEvent event) {
        // 删除商品时，处理分销设置
        handleDistributionAfterDeleteProd(event);
    }

    /**
     * 同步商品状态到分销商品中
     */
    @EventListener(ProdChangeStatusEvent.class)
    @Order(GeneralActivitiesOrder.DISTRIBUTION)
    public void distributionProdChangeStatusListener(ProdChangeStatusEvent event) {
        Product product = event.getProduct();
        Integer status = event.getStatus();
        // 平台下架，商家下架再同步过去
        if (Objects.equals(status, ProdStatusEnums.PLATFORM_OFFLINE.getValue()) && Objects.equals(status, ProdStatusEnums.SHOP_OFFLINE.getValue())) {
            return;
        }
        // 同步商品状态到分销商品
        Long prodId = product.getProdId();
        DistributionProd distributionProd = distributionProdService.getOne(new LambdaUpdateWrapper<DistributionProd>().eq(DistributionProd::getProdId, prodId));
        if (Objects.isNull(distributionProd) || Objects.equals(distributionProd.getState(), ProdStatusEnums.PLATFORM_OFFLINE.getValue())) {
            return;
        }
        if (Objects.equals(status, ProdStatusEnums.PLATFORM_OFFLINE.getValue()) || Objects.equals(status, ProdStatusEnums.AUDIT.getValue())) {
            status = DistributionProdStateEnum.PUT_OFF.getValue();
        }
        distributionProdService.updateState(distributionProd.getDistributionProdId(),status);
        // 清理一下缓存
        distributionProdService.removeDistributionProdPoCacheByProdId(prodId);
    }

    /**
     * 删除商品时，处理分销设置
     * @param event 事件
     */
    private void handleDistributionAfterDeleteProd(ProdChangeEvent event) {
        if (Objects.isNull(event.getProduct())
                || Objects.isNull(event.getProduct().getProdId())) {
            return;
        }
        Long prodId = event.getProduct().getProdId();
        // 获取系统分销配置
        DistributionConfigVO distributionConfigVO = sysConfigService.getSysConfigObject(Constant.DISTRIBUTION_CONFIG, DistributionConfigVO.class);
        if (Objects.isNull(distributionConfigVO)
                || !Objects.equals(distributionConfigVO.getAutoCheck(), AutoCheckEnum.SYSTEM.getValue())) {
            return;
        }
        // 没有指定购买商品 或 删除商品不在指定购买商品内，无需处理
        List<Long> prodIds = distributionConfigVO.getProdIdList();
        if (CollectionUtils.isEmpty(prodIds)
                || !prodIds.contains(prodId)) {
            return;
        }
        log.info("商品[{}]删除，更新分销配置", prodId);
        prodIds.remove(prodId);
        // '系统判定'的申请条件全为空，自动切换成'人工判定'
        if (CollectionUtils.isEmpty(prodIds)
                && Objects.isNull(distributionConfigVO.getExpenseNumber())
                && Objects.isNull(distributionConfigVO.getExpenseAmount())) {
            distributionConfigVO.setAutoCheck(AutoCheckEnum.ARTIFICIAL.getValue());
        }
        sysConfigService.updateValueByKey(Constant.DISTRIBUTION_CONFIG, Json.toJsonString(distributionConfigVO));
    }
}
